package com.example.helloworld;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

	private Button button1;
	private SharedPreferences preferences;
	private EditText edittext1;
	private TextView textview1;
	private MyReceiver receiver;
	private CheckBox checkBox;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		checkBox = (CheckBox) findViewById(R.id.checkBox1);
		button1 = (Button) findViewById(R.id.buttonshowtext);
		edittext1 = (EditText) findViewById(R.id.editText1);
		textview1 = (TextView) findViewById(R.id.textView1);

		button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String s = edittext1.getText().toString();
				textview1.setText(s);
			}
		});

		// start activity
		findViewById(R.id.buttoncallactivity).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						Bundle bundle = new Bundle();
						bundle.putString("msg", "from mainactivity");
						Intent intent = new Intent(MainActivity.this,
								Activity_2.class);
						intent.putExtras(bundle);
						// startActivity(intent);
						startActivityForResult(intent, 0);
						Log.v("mainactivity", "after start activity_2");

					}
				});

		// broadcast
		findViewById(R.id.buttonbroadcast).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						System.out.println("sendBroadcast");
						Bundle bundle = new Bundle();
						bundle.putString("msg", "broadcast");
						Intent in = new Intent();
						in.setAction("actionString");
						in.putExtras(bundle);
						sendBroadcast(in);
					}
				});

		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("actionString");
		registerReceiver(receiver, filter);

		// show Dialog
		findViewById(R.id.buttonshowdlg).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						new AlertDialog.Builder(MainActivity.this)
								.setTitle("test Dialog")
								.setMessage("this is a dialog")
								.setPositiveButton("OK",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface arg0,
													int arg1) {
												Toast.makeText(
														MainActivity.this,
														"you pressed OK button",
														Toast.LENGTH_LONG)
														.show();
											}
										})
								.setNegativeButton("Cancel",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												// TODO Auto-generated method
												// stub
												NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
												Notification notification = new Notification(
														R.drawable.ic_launcher,
														"this is a notification",
														System.currentTimeMillis());
												PendingIntent intent = PendingIntent
														.getActivity(
																MainActivity.this,
																0, getIntent(),
																0);
												notification
														.setLatestEventInfo(
																MainActivity.this,
																"title of notification",
																"content of notification",
																intent);
												notificationManager.notify(
														R.drawable.ic_launcher,
														notification);
												// notificationManager.cancelAll();
											}
										}).show();
					}
				});

		preferences = getPreferences(MODE_PRIVATE);
		checkBox.setChecked(preferences.getBoolean("checkbox", false));
		edittext1.setText(preferences.getString("text", ""));

		// fileStream
		findViewById(R.id.buttonreadfile).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						try {
							InputStream inputStream = MainActivity.this
									.getAssets().open("sample");
							byte[] b = new byte[1024];
							int i = -1;
							StringBuffer sb = new StringBuffer();
							while ((i = inputStream.read(b)) != -1) {
								sb.append(new String(b, 0, i));
							}
							String content = sb.toString();
							textview1.setText(content);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});

		// DB
		findViewById(R.id.buttondb).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				DBHelper dbHelper = new DBHelper(MainActivity.this, "my.db",
						null, 1);

				textview1.setText(dbHelper.getNames());
			}
		});

		// socket
		findViewById(R.id.buttonconect).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						new Thread() {
							public void run() {
								try {
									Socket socket = new Socket("10.0.2.2", 9999);
									DataOutputStream dos = new DataOutputStream(
											socket.getOutputStream());
									dos.writeUTF("from android client's msg");
								} catch (Exception e) {
									Log.v("Exception", e.toString());
								}
							}
						}.start();
					}
				});
		// Web
		findViewById(R.id.button1web).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this,
						Activity_Web.class);
				startActivity(intent);
			}
		});

		// http get
		findViewById(R.id.buttonget).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new Thread() {
					public void run() {
						String text = MyHttp.get("http://10.0.2.2/test.php");
						Message.obtain(handler, 0, text).sendToTarget();
					}
				}.start();
			}
		});

		// http post
		findViewById(R.id.buttonpost).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread() {
					public void run() {
						String text = MyHttp.post("http://10.0.2.2/test.php");
						Message.obtain(handler, 1, text).sendToTarget();
					}
				}.start();
			}
		});
		
		//contact
		findViewById(R.id.buttoncontact).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Cursor cursor = getContentResolver().query(Uri.withAppendedPath(ContactsContract.AUTHORITY_URI, "data/phones"), null, null, null, null);
				cursor.moveToFirst();
				String number = cursor.getString(cursor  
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				textview1.setText(cursor.getString(0));
			}
		});
		
		//draw
		findViewById(R.id.buttondraw).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				startActivity(new Intent(MainActivity.this,SurfaceActivity.class));
			}
		});
	}

	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			textview1.setText(msg.obj.toString());
			super.handleMessage(msg);
		}		
	};
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (data != null && requestCode == 0 && resultCode == 1)
			textview1.setText(data.getExtras().getString("msg"));
		super.onActivityResult(requestCode, resultCode, data);
	}

	public class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			textview1.setText(intent.getExtras().getString("msg"));
		}
	}

	protected void onDestroy() {
		System.out.println("onDestroy");
		Editor editor = preferences.edit();
		editor.putBoolean("checkbox", checkBox.isChecked());
		editor.putString("text", checkBox.isChecked() ? edittext1.getText()
				.toString().trim() : "");
		editor.commit();
		super.onDestroy();
	}

	protected void onPause() {
		System.out.println("pause");
		super.onPause();
	}

	protected void onRestart() {
		System.out.println("restart");
		super.onRestart();
	}

	protected void onResume() {
		System.out.println("resume");
		super.onResume();
	}

	protected void onStart() {
		System.out.println("start");
		super.onStart();
	}

	protected void onStop() {
		System.out.println("stop");
		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
